package cn.majingjing.demo.aop.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;

/**
 * @author JingjingMa
 * @date 2019/11/4 14:04
 */
@Configuration
public class ScheduleConfig implements SchedulingConfigurer {

    private static ScheduledTaskRegistrar scheduledTaskRegistrar;
    private static ScheduledExecutorService currentScheduledExecutorService;

    @Override
    public void configureTasks(ScheduledTaskRegistrar scheduledTaskRegistrar) {
        ScheduleConfig.scheduledTaskRegistrar = scheduledTaskRegistrar;
        ScheduleConfig.currentScheduledExecutorService = Executors.newScheduledThreadPool(10);
        scheduledTaskRegistrar.setScheduler(ScheduleConfig.currentScheduledExecutorService);
    }

    public static ScheduledTaskRegistrar getScheduledTaskRegistrar() {
        return ScheduleConfig.scheduledTaskRegistrar;
    }

    /**
     * 重新调度
     */
    public static void reScheduler() {
        if (ScheduleConfig.currentScheduledExecutorService != null) {
            ScheduleConfig.currentScheduledExecutorService.shutdown();
        }
        ScheduleConfig.currentScheduledExecutorService = Executors.newScheduledThreadPool(10);
        ScheduleConfig.scheduledTaskRegistrar.setScheduler(ScheduleConfig.currentScheduledExecutorService);

        ScheduleConfig.scheduledTaskRegistrar.getCronTaskList().forEach(x-> ScheduleConfig.scheduledTaskRegistrar.getScheduler().schedule(x.getRunnable(),x.getTrigger()));

    }

}
